/*
 * Copyright 2018 the original author or authors.
 *
 * you can use the file or import project.but Do not take legal responsibility.
 * Only for learning communication.
 *
 * Java compiled version 1.8 or higher
 *
 *
 *
 *
 */

package org.liang.javasource.config;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Properties;

public class ConfigFactory {
    private static ClassConfig classConfig=null;
    
    private static Properties pros = new Properties();

    public static ClassConfig newInstance() {
	if(classConfig == null) {
	    try {
		initConfig();
	    } catch (IOException e) {
		e.printStackTrace();
	    }
	}
	
	return classConfig;
    }
    
    public static void main(String[] args) {
	ClassConfig classConfig = ConfigFactory.newInstance();
	System.out.println(classConfig);
    }
    
    /*
     * 加载资源文件
     */
    private static void loadProp() throws IOException {
	InputStream inStream = ConfigFactory.class.getClassLoader().getResourceAsStream("application.properties");
	pros.load(new InputStreamReader(inStream,"UTF-8"));
    }
    
    /*
     * 初始化配置信息
     */
    private static void initConfig() throws IOException {
	
	classConfig = new ClassConfig();
	loadProp();
	classConfig.author = getProperty("app.author","auto",String.class);
	classConfig.classSuffix = getProperty("app.classSuffix","",String.class);
	classConfig.firstToLowercase = getProperty("app.firstToLowercase",false,Boolean.class);
	classConfig.baseDtoRule = getProperty("app.baseDtoRule",false,Boolean.class);
	classConfig.arrToList = getProperty("app.arrToList",false,Boolean.class);
	classConfig.filePath = getProperty("app.filePath","",String.class);
	classConfig.createPath = getProperty("app.createPath","auto",String.class);
	classConfig.packageName = getProperty("app.packageName","auto",String.class);
	classConfig.sheets = getProperty("app.sheets",new Integer[] {0},Integer[].class);
	
    }
    
    @SuppressWarnings("unchecked")
    private static <T> T getProperty(String key,T defaultValue,Class<T> type) {
	Object value = pros.get(key);
	if(value == null || "".equals(value.toString())) {
	    return defaultValue;
	}
	//boolean 类型转换
	if(type.getTypeName().equals("java.lang.Boolean")) {
	    return (T) new Boolean(value.toString());
	}
	//数组转换
	//TODO 目前只针对项目中Integer数组类型处理
	if(type.isArray()) {
	    String[] array = value.toString().split(",");
	    Integer[] arrInt =  Arrays.stream(array).map(x -> new Integer(x)).toArray(Integer[] :: new);
	    return (T) arrInt;
	}
	
	return type.cast(value);
    }
    
}
